<?php
include_once('AVRestClient.class.php');
error_reporting( E_ALL&~E_NOTICE );
header("Content-type: text/html; charset=utf-8");

//没有函数直接开始执行
//1、执行自动更新闪购商品问题
$goods = new \Avos\AVQuery('ECGoods');
$goods->where('status',4);
$goods->whereLessThanOrEqualTo('flashEndTime',array('__type'=>'Date','iso'=>date("Y-m-d\TH:i:s\.",time(true)-8*3600).'000Z'));
$res = $goods->find();
if(!empty($res->error)) {
    $content = $res->error;
    logInfo($content);
}
if(empty($res->results)) {
    $content = '自动更新，没有闪购商品';
    logInfo($content);
}
//如果寻找到该满足的商品，遍历更新
$success = 0;
$statusUp = 0;
$error = 0;
$hasNo = 0;
foreach($res->results as $k => $v) {
    $status_updated = updateFlashStatus($v->objectId);
    //寻找主页闪购类里面的商品是否有该商品，若有则删除该记录
    if($status_updated->error) {
        $content = $status_updated->error;
        logInfo($content);
    }else{
        $statusUp++;
        $flash_update = lookFlashGood($v->objectId);
        switch($flash_update) {
            case 1 : $success++ ;break;
            case 0 : $hasNo++;   break;
            case -1: $error++;   break;
            default : $hasNo++;   break;
        }
    }
}
$content = "自动更新信息如下：\n共寻找到超过闪购商品：".count($res->results)."条。\n其中修改商品状态成功：".$statusUp."条。\n修改主页flash信息成功：".$success."条。\n修改主页flash信息失败：".$error."条。\n没有找到的主页flash信息：".$hasNo."条。\n";
logInfo($content);

function logInfo($content) {
    $log = new \Avos\AVObject('ECLog');
    $log->content = $content;
    $log->options = '自动更新闪购';
    $log->money = 0;
    $log->type = 1;
    $log->save();
    output($content);
    exit;
}

function lookFlashGood($object) {
    $main = new \Avos\AVQuery('ECFlashGood');
    $main->wherePointer('good','ECGoods',$object);
    $main->setCount(true);
    $res = $main->find();
    if($res->count) {
        //闪购信息
        $flash = new \Avos\AVObject('ECFlashGood');
        $results = $flash->delete($res->results[0]->objectId);
        if($results) {
            return 1;
        }else {
            logInfo($results->error);
            return -1;
        }
    }else{
        return 0;
    }
}

function updateFlashStatus($object) {
    $good = new \Avos\AVObject('ECGoods');
    $good->status = 1;
    $res = $good->update($object);
    return $res;
}

function output($content) {
    echo "*********************Tedo Auto Update Log Info*******************\n".
         "***Time:".date("Y-m-d H:i:s",time())."***************************\n".
         "***Log: ".$content."*********************************************\n".
         "*****************************************************************\n".
         "\n\n\n";
}

